package main

import (
	"context"
	"fmt"
	"time"

	"github.com/coreos/etcd/clientv3"
)

func main() {
	var (
		conf   clientv3.Config
		client *clientv3.Client
		err    error
		kv     clientv3.KV
		rsp    *clientv3.PutResponse
		getRsp *clientv3.GetResponse
		// delRsp    *clientv3.DeleteResponse
		lease     clientv3.Lease
		grantResp *clientv3.LeaseGrantResponse
		leaseID   clientv3.LeaseID
		// leaseRep  <-chan *clientv3.LeaseKeepAliveResponse
	)
	//set conf
	conf = clientv3.Config{
		Endpoints:   []string{"127.0.0.1:2379"},
		DialTimeout: 5 * time.Second,
	}

	//new client
	if client, err = clientv3.New(conf); err != nil {
		fmt.Println(err)
		return
	}

	lease = clientv3.NewLease(client)
	if grantResp, err = lease.Grant(context.TODO(), 5); err != nil {
		fmt.Println(err)
	}

	leaseID = grantResp.ID

	// set heart beat
	_, err = lease.KeepAlive(context.TODO(), leaseID)
	// put KV
	kv = clientv3.NewKV(client)
	if rsp, err = kv.Put(context.TODO(), "/user/local", ".......", clientv3.WithLease(leaseID)); err != nil {
		println(err)
	} else {
		println(rsp.Header.Revision)
	}

	for {
		//get
		if getRsp, err = kv.Get(context.TODO(), "/user/local"); err != nil {
			fmt.Println(err)
		}

		if getRsp.Count > 0 {
			fmt.Println("exist~~~~")
		} else {
			fmt.Println("not found")
			return
		}
		time.Sleep(time.Second)
	}

}
